package com.qs.security.controller;

import cn.hutool.json.JSONUtil;
import com.qs.security.model.UserDTO;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ResourceController {

    @GetMapping(value = "/res1")
    @PreAuthorize("hasAuthority('p1')")//拥有p1权限方可访问此url
    public String r1() {
        //获取用户身份信息
        UserDTO userDTO = JSONUtil.toBean(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(),
                UserDTO.class);
        return userDTO.getFullname() + "访问资源1";
    }

    @GetMapping(value = "/res2")
    @PreAuthorize("hasAuthority('p2')")//拥有p2权限方可访问此url
    public String r2() {
        //获取用户身份信息
        UserDTO userDTO = (UserDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return userDTO.getFullname() + "访问资源2";
    }
}
